#include <linux/init.h>
#include <linux/module.h>
#include <linux/i2c.h>


// maybe is 0x29<<1
#define VL6180_ADDR 0x29

MODULE_LICENSE("Dual BSD/GPL");

struct i2c_client* vl6180_client;
struct i2c_adapter* vl6180_adapter;

// write index reg with value
void vl6180_write(int index, int value)
{
	unsigned char wbuf[3];
	struct i2c_msg msg;
	msg.addr = VL6180_ADDR<<1;
	msg.flags = 0; // write
	msg.len = 3;
	msg.buf = wbuf;
	wbuf[0] = index & (0xFF<<8);
	wbuf[1] = index & (0xFF<<0);
	wbuf[2] = value;

	vl6180_adapter->algo->master_xfer(vl6180_adapter, &msg, 1);
}

// read index reg's value
int vl6180_read(int index)
{

	unsigned char value;
	unsigned char wbuf[2];

	// do a write of index to vl6180
	struct i2c_msg msg;
	msg.addr = VL6180_ADDR<<1;
	msg.flags = 0; // write
	msg.len = 2;
	msg.buf = wbuf;
	wbuf[0] = index & (0xFF<<8);
	wbuf[1] = index & (0xFF<<0);
	vl6180_adapter->algo->master_xfer(vl6180_adapter, &msg, 1);

	// read one byte from vl6180
	msg.addr = VL6180_ADDR<<1;
	msg.flags = I2C_M_RD;
	msg.len = 1;
	msg.buf = &value;
	vl6180_adapter->algo->master_xfer(vl6180_adapter, &msg, 1);

	return value;
}

int vl6180_probe(struct i2c_client *client, const struct i2c_device_id * devid)
{

	printk("vl6180_probe\n");
	vl6180_client = client;
	vl6180_adapter = i2c_get_adapter(1); // vl6180 is connected to I2C-1
		

	// read to see if can read chip ID out, correctly
	printk("vl6180 IDENTIFICATION__MODEL_ID is 0x%x\n", vl6180_read(0x000));
	return 0;
}

int vl6180_remove(struct i2c_client *client)
{
	printk("vl6180_remove\n");
	return 0;
}

static const struct i2c_device_id vl6180_id[] = {
	    { "vl6180",  0 },
		{ }
};

MODULE_DEVICE_TABLE(i2c, vl6180_id);

static struct i2c_driver vl6180_i2c_driver = {
	.driver = {
		.name = "vl6180",
	},
	.probe    = vl6180_probe,
	.remove   = vl6180_remove,
	.id_table = vl6180_id,
};

static int __init vl6180_module_init(void)
{
	printk("vl6180_module_init\n");
	return i2c_add_driver(&vl6180_i2c_driver);
}

static void __exit vl6180_module_exit(void)
{
	printk("vl6180_module_exit\n");
	i2c_del_driver(&vl6180_i2c_driver);
}

module_init(vl6180_module_init);
module_exit(vl6180_module_exit);

